package com.helen.mybatis.parse;

import com.helen.mybatis.configration.Configuration;
import com.helen.mybatis.configration.MappedStatement;
import com.mysql.cj.util.StringUtils;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.InputStream;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

import static java.lang.Class.forName;

/**
 * @author helenlee
 * @date 2020/4/8
 */
public class XmlMappedStatementBuilder {
    public static void build(Configuration configuration, String path) throws DocumentException, ClassNotFoundException {
        InputStream resourceAsStream = ClassLoader.getSystemResourceAsStream(path);
        SAXReader saxReader = new SAXReader();
        Document document = saxReader.read(resourceAsStream);
        Element rootElement = document.getRootElement();
        String namespace = rootElement.attributeValue("namespace");
        // select 节点
        List<Element> selectNodes = rootElement.selectNodes("//select");
        buildMappedStatement(configuration,selectNodes,namespace);

        // insert 节点
        List<Element> insertNodes = rootElement.selectNodes("//insert");
        buildMappedStatement(configuration,insertNodes,namespace);


        // delete 节点
        List<Element> deleteNodes = rootElement.selectNodes("//delete");
        buildMappedStatement(configuration,deleteNodes,namespace);

        // update 节点
        List<Element> updateNodes = rootElement.selectNodes("//update");
        buildMappedStatement(configuration,updateNodes,namespace);

    }

    private static void buildMappedStatement(Configuration configuration, List<Element> selectNodes, String namespace) throws ClassNotFoundException {
        for (Element select : selectNodes) {
            String id = select.attributeValue("id");
            String paramType = select.attributeValue("paramType");
            String resultType = select.attributeValue("resultType");
            String textTrim = select.getTextTrim();
            MappedStatement mappedStatement = new MappedStatement();
            mappedStatement.setId(id);
            mappedStatement.setSql(textTrim);
            mappedStatement.setConfiguration(configuration);
            Class<?> aClass = StringUtils.isNullOrEmpty(paramType)?void.class:forName(paramType);
            mappedStatement.setParamType(aClass);
            Class<?> bClass = StringUtils.isNullOrEmpty(paramType)?void.class:forName(resultType);
            mappedStatement.setResultType(bClass);
            configuration.getMappedStatementMap().put(namespace + "." + id, mappedStatement);
        }
    }
}
